﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using App.Web.ViewModels;
using App.Domain;
using App.Web.Utility;
using AutoMapper;
using App.Core.Authentication;
using App.Core.Extensions;
using System.Text;

namespace App.Web.Controllers
{
    public class AccountController : BaseController
    {
        private AppEntities _Context = new AppEntities();
        
        public AccountController()
        {            
        }

        public AccountController(UserViewModel currentUser)
            : base(currentUser)
        {
        }
        
        #region Action Methods

        public ActionResult LogOn(string productId = "")
        {            
            SessionCache.AddFavoriteProductID = productId.IsNullOrEmpty() ? 0 : productId.ToInt();
            ViewBag.LogOnMessage = (productId != "") ? "Sorry! You are not logged in." : "Log On";
            return View();
        }

        //
        // POST: /Account/LogOn

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                User user = _Context.Users.FirstOrDefault(P => String.Compare(P.UserName, model.UserName, true) == 0 && String.Compare(P.Password, model.Password, true) == 0);
                if(user == null)
                    ModelState.AddModelError(AppConstants.Validation.INVALID_USER, "Sorry! The user name or password provided is incorrect.");
                else if(!user.IsActive)
                    ModelState.AddModelError(AppConstants.Validation.INVALID_USER, "Sorry! The user is currently inactive.");
                else
                {
                    UserViewModel userViewModel = null;
                    userViewModel = Mapper.Map<User, UserViewModel>(user, userViewModel);
                    userViewModel.Group = Mapper.Map<GroupViewModel>(user.Group);
                    WebUtil.LoadCompanyInfo(userViewModel, user, _Context);
                    if (userViewModel.Company != null && !userViewModel.Company.IsActive)
                        ModelState.AddModelError(AppConstants.Validation.INVALID_USER, "Sorry! The user is currently inactive.");
                    else
                    {
                        SessionCache.CurrentUser = userViewModel;
                        //FormsAuthenticationUtil.RedirectFromLoginPage(model.UserName, userViewModel.Group.Name, model.RememberMe);
                        FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);


                        ///
                        /// Check the logon page request come from add to fvt or not
                        ///
                        int productID = SessionCache.AddFavoriteProductID;
                        if (productID > 0)
                        {
                            AddToFavorite(productID);
                            SessionCache.AddFavoriteProductID = 0; 
                            return RedirectToAction("Index", "Private/Favorites");
                        }
                        else
                        {
                            
                            if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                                && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                            {
                                return Redirect(returnUrl);
                            }
                            else
                                FormsAuthentication.RedirectFromLoginPage(model.UserName, model.RememberMe);
                            //return RedirectToAction("Index", "Home");
                        }
                    }
                }
            }
            return View(model);
        }

        public void AddToFavorite(int productID)
        {
            //int intProductID = productID.ToInt();
            var myFavorite = _Context.UserWishLists.FirstOrDefault(P => P.UserID == SessionCache.CurrentUser.ID
                && P.ProductID == productID);

            UserWishList entity = null;

            if (myFavorite == null)
            {
                entity = new UserWishList();
                _Context.AddToUserWishLists(entity);
                entity.UserID = SessionCache.CurrentUser.ID;
                entity.ProductID = productID;
                entity.UpdatedDate = System.DateTime.Now;
                entity.IsActive = true;

                _Context.SaveChanges();
            }
            else
            {
                entity = myFavorite;
                entity.IsActive = (myFavorite.IsActive) ? false : true;
                entity.UpdatedDate = System.DateTime.Now;

                _Context.SaveChanges();
            }
        }

        //
        // GET: /Account/LogOff

        public ActionResult LogOff()
        {
            SessionCache.ClearSession();
            FormsAuthentication.SignOut();            
            return RedirectToAction("Index", "Home");
        }

        //
        // GET: /Account/Register

        public ActionResult Register(String msg = "")
        {
            ViewBag.IsRegistrationSuccess = msg.IsEmpty() ? null : msg;
            return View();
        }

        //
        // POST: /Account/Register

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                if (_Context.IsDuplicateEmail(model.Email))
                    ModelState.AddModelError("", "Given user name already taken. Please choose another.");
                else
                {
                    User user = new User();
                    user.UserName = model.Email;
                    user.Password = model.Password;
                    user.GroupID = ConfigReader.UserGroupIDOfSiteUser;
                    user.IsActive = true;

                    _Context.AddToUsers(user);
                    _Context.SaveChanges();

                    sendNotificationToSiteUser(user);
                    
                    return RedirectToAction("Register", new { msg = "True" });
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        private void sendNotificationToSiteUser(User user)
        {
            StringBuilder template = new StringBuilder(WebUtil.ReadEmailTemplate(AppConstants.EmailTemplate.COMMON));
            if (template.Length > 0)
            {
                StringBuilder sb = new StringBuilder();
                //sb.AppendFormat("Dear Admin,<br/>");
                sb.AppendFormat("Thank you for registering in {0}. Your user name and passwords are -.<br /><br />", ConfigReader.SiteName);
                sb.AppendFormat("User Name: {0}<br />Password: {1}",user.UserName,user.Password);
                
                ///Proejct Details
                //sb.Append("<br /><br />");
                template.Replace(AppConstants.ETConstants.DOMAIN, WebUtil.GetDomainAddress());
                template.Replace(AppConstants.ETConstants.MESSAGE, sb.ToString());
                String fromEmail = ConfigReader.SupportEmail;
                String toEmail = String.Empty;//ConfigReader.AdminEmail;
                toEmail = user.UserName;
                
                String subject = String.Format("User information for {0}.", ConfigReader.SiteName);
                WebUtil.SendMail(fromEmail, toEmail, String.Empty, String.Empty, subject, template.ToString());
            }
        }

        //
        // GET: /Account/ChangePassword

        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        //
        // POST: /Account/ChangePassword

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {

                // ChangePassword will throw an exception rather
                // than return false in certain failure scenarios.
                bool changePasswordSucceeded;
                try
                {
                    MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
                    changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePasswordSuccess

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        #endregion Action Methods

        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion

        #region Helper Methods
        
        #endregion
    }
}
